<template>
  <el-dialog v-model="relatedDialogFormVisible" title="关联用户" width="500">
    <el-tree
      ref="treeRef"
      style="max-width: 600px"
      node-key="id"
      show-checkbox
      check-strictly
      default-expand-all
      :data="treeData"
      :props="defaultProps"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button @click="addClick">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, defineProps, defineEmits } from "vue";
import { ElMessage } from "element-plus";
import http from "../../../../util/http.js";
import { el } from "element-plus/es/locales.mjs";
// 自定义属性
const props = defineProps({
  relatedFormVisible: Boolean,
  role: Object,
});
const relatedDialogFormVisible = ref(props.relatedFormVisible);

// 自定义事件
const emit = defineEmits(["update:relatedFormVisible"]);
// 监听relatedFormVisible、fetchRoleMenus属性
watch(
  () => props.relatedFormVisible,
  (newVal) => {
    relatedDialogFormVisible.value = newVal;
    if (newVal) {
      fetchRoleMenus();
    }
  },
  { immediate: true } //在组件挂载时立即执行一次
);
// 监听relatedDialogFormVisible变化，关闭对话框
watch(relatedDialogFormVisible, (newVal) => {
  if (!newVal) {
    emit("update:relatedFormVisible", false);
  }
});

// 关闭对话框
const closeDialog = () => {
  relatedDialogFormVisible.value = false;
  emit("update:relatedFormVisible", false);
};

//树状菜单
const treeRef = ref(null);
const treeData = ref<TreeNode[]>([]);
const defaultProps = {
  children: "children",
  label: "text",
};
// 树节点属性接口
interface TreeNode {
  id: string;
  text: string;
  icon: string;
  url: string;
  pid: string;
  order: number;
  flag: string;
  children?: TreeNode[];
}
// 菜单加载

const initTableData = async () => {
  try {
    const response = await http.post("/menu/menutable");
    const result = response.data.rows;
    treeData.value = convertToTree(result);
    // console.log(treeData.value);
  } catch (error) {
    ElMessage.error("菜单加载错误" + error);
  }
};
// 将数据转换为树状
const convertToTree = (data: TreeNode[]): TreeNode[] => {
  const result: TreeNode[] = [];
  const map: { [key: string]: TreeNode } = {};

  data.forEach((item) => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach((item) => {
    if (item.pid === "0") {
      result.push(map[item.id]);
    } else {
      if (map[item.pid]) {
        map[item.pid].children.push(map[item.id]);
      }
    }
  });

  return result;
};
// 读取角色菜单数据
// const checkedKeys = ref();
const result = [];
const fetchRoleMenus = async () => {
  if (props.role && props.role.id) {
    try {
      const response = await http.post("/menu/getrolemenutable", {
        id: props.role.id,
      });
      const rows = response.data.rows;
      const checkedKeys = rows.map((row) => row.id);
      const key = checkedKeys;
      treeRef.value.setCheckedKeys(key);
    } catch (error) {
      ElMessage.error("加载角色菜单失败");
    }
  } else {
    console.log("有错误");
  }
};
// 提交功能
//读取选中的数节点
const addClick = async () => {
  if (props.role && props.role.id) {
    const menuid = treeRef.value.getCheckedKeys();
    try {
      await http.post(
        "/roles/addrolemenu",
        {
          id: props.role.id,
          body: JSON.stringify(menuid),
        },
        true
      );
      

      ElMessage.success("添加成功");
      relatedDialogFormVisible.value = false;
      emit("update:relatedFormVisible", false);
    } catch (error) {
      ElMessage.error("加载角色菜单失败");
    }
  } else {
    console.log("有错误");
  }
};
onMounted(() => {
  initTableData();
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
